var mongoose = require('mongoose');
var News = mongoose.model('News');

module.exports = {
    create: function(req,res,next){
        var news = new News(req.body);
        news.save(function(err){
            if(err){
                return next(err);
            }
            return res.json(news);
        })
    },

    list: function(req,res,next){
        var page = parseInt(req.query.page, 1) || 1;
        var rows = parseInt(req.query.rows, 10) || 10;

        News
        .find()
        .skip((page -1)*rows)
        .limit(rows)
        .exec(function(err,docs){
            if(err){
                return next(err);
            }

            return res.json(docs);
        });
    },

    getById: function(req,res,next,id){
        if(!id){
            return next(new Error('News not found!'));
        }

        News
            .findOne({_id: id})
            .exec(function(err,doc){
                if(err){
                    return next(err);
                }

                if(!doc){
                    return next(new Error('News not found!'));
                }

                req.news = doc;

                return next();
            });
    },

    get: function(req,res,next){
        return res.json(req.news);
    }
}